package com.wyzz.hr.spring;

import com.wyzz.hr.report.engine.BirtEngine;
import com.wyzz.hr.report.engine.BirtEngineFactory;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringBeanFactory implements ServletContextListener {

	public SpringBeanFactory() {
	}

	public static Object getBean(String name) {
		if (!beanCache.containsKey(name))
			beanCache.put(name, context.getBean(name));
		return beanCache.get(name);
	}

	public static ApplicationContext getSpringContext() {
		return context;
	}

	public void contextInitialized(ServletContextEvent event) {
		ServletContext application = event.getServletContext();
		contextLoader = new ContextLoader();
		contextLoader.initWebApplicationContext(application);
		context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(application);
		BirtEngine.getBirtEngine(application);
		BirtEngineFactory.getBirtDesignEngine(application);
	}

	public void contextDestroyed(ServletContextEvent event) {
		BirtEngine.destroyBirtEngine();
		System.gc();
		contextLoader.closeWebApplicationContext(event.getServletContext());
	}

	public static void setApplicationContext(ApplicationContext cxt) {
		context = cxt;
	}

	private static ApplicationContext context = null;
	private ContextLoader contextLoader;
	private static Map beanCache = new HashMap();

}
